package com.talent.web.exception;//package com.talent.web.exception;


import com.talent.web.enums.ResponseEnum;
import com.talent.web.model.TalentResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
 * @ClassName：GlobalExceptionHandler
 * @Author: hszhou
 * @Date: 2024/10/21 13:35
 * @Description: 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(NullPointerException.class)
    public TalentResult<String> nullPointException(NullPointerException e) {
        e.printStackTrace();
        return TalentResult.error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public TalentResult<ResponseEnum> exception(Exception e) {
       e.printStackTrace();
        return TalentResult.error(ResponseEnum.ERROR);
    }

    /**
     * 处理认证异常（用户名密码错误、账号禁用等）
     * @param ex
     * @return
     */
    @ExceptionHandler(AuthenticationException.class)
    public TalentResult<ResponseEnum> handleAuthenticationException(
            AuthenticationException ex) {

        // 根据具体异常类型细化错误信息
        if (ex instanceof BadCredentialsException) {
            logger.info("进入全局异常处理器");
            ex.printStackTrace();
          logger.info(  ex.getMessage());
            return TalentResult.error(ex.getMessage());
        }
        // 构建统一响应结构
        return TalentResult.error(ex.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public TalentResult<String> handleValidException(MethodArgumentNotValidException ex){

        StringBuilder msg = new StringBuilder();
        BindingResult bindingResult = ex.getBindingResult();
        for (ObjectError error : bindingResult.getAllErrors()) {
            if(error instanceof FieldError){
                msg.append(((FieldError) error).getField())
                        .append(":");
            }
            msg.append(error.getDefaultMessage()==null?"":error.getDefaultMessage());
        }

        return TalentResult.error(ex.getBindingResult().toString());
    }
}
